package study.elasticsearch.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import study.elasticsearch.util.HtmlParseUtil;
import study.elasticsearch.vo.JdHtmlContent;
import study.elasticsearch.vo.User;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class EsService {
    public static final String JD_GOODS_INDEX = "jd_goods";
    @Autowired
    private RestHighLevelClient client;

    public boolean addContent(String keyWord) throws Exception {
        List<JdHtmlContent> list = HtmlParseUtil.parseJD(keyWord);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("1m");
        for(int i = 0 ; i <list.size(); i++){
            ObjectMapper mapper = new ObjectMapper ();
            String json = mapper.writeValueAsString(list.get(i));
            //构造 IndexRequest
            IndexRequest indexRequest = new IndexRequest(JD_GOODS_INDEX).id(""+(i+1)).source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("是否成功："+!bulkResponse.hasFailures());
        return !bulkResponse.hasFailures();
    }

    public  List<Map<String,Object>> search(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo < 1){
            pageNo =1;
        }
        SearchRequest request = new SearchRequest(JD_GOODS_INDEX);
        //构建条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //高亮
        HighlightBuilder highlight = new HighlightBuilder();
        highlight.preTags("<font color=red>");
        highlight.postTags("</font>");
        highlight.field("title");
        highlight.requireFieldMatch(false); //匹配多个字段，均高亮
        searchSourceBuilder.highlighter(highlight);
        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);
        //QueryBuilders.termQuery精确查询
        //QueryBuilders.matchAllQuery() 匹配所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title",keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //条件绑定到request中
        request.source(searchSourceBuilder);
        //查询操作
        SearchResponse searchResponse = client.search(request,RequestOptions.DEFAULT);
        List<Map<String,Object>>  list =  new ArrayList();
        //解析结果
        for(SearchHit hit :searchResponse.getHits().getHits()){
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            System.out.println(sourceAsMap);
            //替换高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField nameHighlight = highlightFields.get("title");
            if (nameHighlight != null) {
                Text[] fragments = nameHighlight.getFragments();
                String _title = "";
                for (Text text : fragments) {
                    _title += text;
                }
                sourceAsMap.put("title", _title);
            }
            list.add(sourceAsMap);
        }
        return list;

    }

}
